#include "threadPool.h"

void* handleEvent(void* arg){
    threadPool_t* p_threadPool = (threadPool_t*)arg;
    while(1){
        pthread_mutex_lock(&p_threadPool->mutex);
        while(p_threadPool->taskQueue.cursize == 0 && p_threadPool->exitflag == 0){
            pthread_cond_wait(&p_threadPool->cond,&p_threadPool->mutex);
        }
        if(p_threadPool->exitflag == 1){
            // printf("worker is going to exit,tid = %lu\n",pthread_self());  // pthread_self()获取的tid实际上是线程控制块的地址(64位)
            printf("worker is going to exit,tid = %lu\n",syscall(SYS_gettid));
            pthread_mutex_unlock(&p_threadPool->mutex);
            pthread_exit(NULL);
        }
        int netfd = p_threadPool->taskQueue.front->netfd;
        dequeue(&p_threadPool->taskQueue);
        pthread_mutex_unlock(&p_threadPool->mutex);
        sleep(100);   // 处理puts和gets
        printf("worker finish his job,tid = %lu\n",syscall(SYS_gettid));
        close(netfd);
    }
    return NULL;
}

int makeWorker(threadPool_t* p_threadPool){
    for(int i = 0;i < p_threadPool->tidArr.workerNum;i++){
        pthread_create(&p_threadPool->tidArr.arr[i],NULL,handleEvent,p_threadPool);
    }
    return 0;
}
